package com.corpgovernment.permission.service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.corpgovernment.api.organization.model.bookingrelation.UidOrgIdEntry;
import com.corpgovernment.api.permission.vo.SearchUserRoleRequest;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.base.Page;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.utils.BaseUtils;
import com.corpgovernment.common.utils.EncryptUtils;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.entity.db.MbOrgEmployeeInfo;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.operatelog.service.pojo.RoleInfoPojo;
import com.corpgovernment.organization.operatelog.service.pojo.UserRolePojo;
import com.corpgovernment.organization.service.IOrgUserIdCardService;
import com.corpgovernment.organization.service.IOrganizationEmployeeService;
import com.corpgovernment.organization.service.IOrganizationInfoService;
import com.corpgovernment.organization.service.IUserLoginService;
import com.corpgovernment.permission.controller.RoleRest;
import com.corpgovernment.permission.controller.UserRoleRest;
import com.corpgovernment.permission.entity.MbUserRoleInfo;
import com.corpgovernment.permission.entity.db.MbRole;
import com.corpgovernment.permission.entity.db.MbUserRole;
import com.corpgovernment.permission.mapper.RoleMapper;
import com.corpgovernment.permission.mapper.UserRoleMapper;
import com.corpgovernment.permission.vo.ListRoleReq;
import com.corpgovernment.permission.vo.UserRole;
import com.corpgovernment.redis.cache.RoleResourceManager;
import com.ctrip.corp.obt.generic.core.context.RequestContext;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.ctrip.corp.obt.shard.context.PageContext;
import com.ctrip.corp.obt.shard.sql.mybatis.interceptor.pagination.IPage;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.corpgovernment.permission.config.PermissionFilter.DATA_PERMISSION_ORG_ID_LIST;

@Service
@Slf4j
public class UserRoleService implements RelationSrv<UidOrgIdEntry, Long> {

    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleService roleService;
    @Autowired
    private IOrganizationInfoService organizationInfoService;
    @Autowired
    private IUserLoginService userLoginService;
    @Autowired
    private IOrganizationEmployeeService employeeService;
    @Autowired
    private IOrgUserIdCardService orgUserIdCardService;
    @Autowired
    private RoleResourceManager roleResourceManager;

    public List<UserRole> listRole(List<String> roleOrgIds) {
        List<MbUserRole> result = userRoleMapper.listRoleByOrgId(BaseUtils.filterEmpty(roleOrgIds));
        if (CollectionUtils.isEmpty(result)) {
            return null;
        }
        return result.stream().filter(Objects::nonNull).map(this::convertUserRole).collect(Collectors.toList());
    }

    public List<UserRole> listBgRole(String empName) {
        List<MbUserRole> result = userRoleMapper.fuzzyBgRoleByName(empName, null);
        log.info("result:{}", JsonUtils.toJsonString(result));
        if (CollectionUtils.isEmpty(result)) {
            return new ArrayList<>();
        }
        return result.stream().filter(Objects::nonNull).map(this::convertUserRole).collect(Collectors.toList());
    }

    public List<UserRole> listUserRole(UidOrgIdEntry identity, List<String> roleOrgIds) {
        if (identity == null) {
            identity = new UidOrgIdEntry();
        }
        List<String> userOrgIds = Collections.singletonList(identity.getOrgId());
        List<String> uids = Collections.singletonList(identity.getUid());

        return fuzzyByName(null, BaseUtils.filterEmpty(userOrgIds), null, BaseUtils.filterEmpty(uids), BaseUtils.filterEmpty(roleOrgIds));
    }

    private List<UserRole> fuzzyByName(String empName, List<String> userOrgIds, List<Long> roleIds, List<String> uids, List<String> roleOrgIds) {
        List<MbUserRole> result = userRoleMapper.fuzzyByName(empName, userOrgIds, roleIds, uids, roleOrgIds);
        if (CollectionUtils.isEmpty(result)) {
            return null;
        }
        return result.stream().filter(Objects::nonNull).map(this::convertUserRole).collect(Collectors.toList());
    }

    private UserRole convertUserRole(MbUserRole ur) {
        if (ur == null) {
            return null;
        }
        UserRole temp = new UserRole();
        temp.setId(ur.getId());
        temp.setUserId(ur.getUid());
        temp.setRoleId(ur.getRoleId());
        temp.setUserName(ur.getEmpName());
        temp.setUserOrgId(ur.getEmpOrgId());
        temp.setUserOrgName(ur.getEmpOrgName());
        temp.setRoleName(ur.getRoleName());
        temp.setDescription(ur.getRoleDescription());
        temp.setRoleOrgId(ur.getRoleOrgId());
        temp.setRoleOrgName(ur.getRoleOrgName());
        temp.setMobilePhone(ur.getEmpMobilePhone());
        temp.setCountryCode(ur.getEmpAreaCode());
        temp.setDataChangeTime(ur.getDatachangeCreatetime());
        temp.setEmpDeleteTime(ur.getEmpDeleteTime());
        temp.setIsRecManager(ur.getIsRecManager());
        temp.setEmpEmail(ur.getEmpEmail());
        return temp;
    }

    public MbUserRole selectById(Long id){
        return userRoleMapper.selectByPrimaryKey(id);
    }

    public void delete(Long id) {
        userRoleMapper.deleteByPrimaryKey(id);
    }

    public MbRole loadRole(Long userRoleId) {
        MbUserRole ur = userRoleMapper.selectByPrimaryKey(userRoleId);
        if (ur == null) {
            return null;
        }
        MbRole mbRole = roleMapper.selectByPrimaryKey(ur.getRoleId());
        if (mbRole.getIsDeleted()) {
            return null;
        }
        return mbRole;
    }

    private List<String> getAccessibleOrgIdList() {
        // 数据权限管控
        Object orgIds = RequestContext.getCurrentContext().getContextParams(DATA_PERMISSION_ORG_ID_LIST);
        List<String> listOrgIds = new ArrayList<>();
        if (Objects.nonNull(orgIds)) {
            String str = JsonUtils.toJsonString(orgIds);
            if (StringUtils.isNotBlank(str)) {
                log.info("获取到的数据权限为：{}", str);
                listOrgIds = JsonUtils.parseArray(str, String.class);
            }
        }
        return listOrgIds;
    }

    public Page pageQuery(UserRoleRest.UserRolePageReq req) {
        List<String> orgIdList = getAccessibleOrgIdList();

        List<MbOrgEmployeeInfo> employeeInfoList = employeeService.findLikeName(req.getEmpName());
        if (CollectionUtils.isEmpty(employeeInfoList)) {
            return new Page(req.getPageNum(), req.getPageSize(), 0, 0L, Collections.emptyList());
        }

        List<String> uids = employeeInfoList.stream().map(MbOrgEmployeeInfo::getUid).collect(Collectors.toList());
        Map<String, MbOrgEmployeeInfo> employeeMap = employeeInfoList.stream().collect(Collectors.toMap(MbOrgEmployeeInfo::getUid, Function.identity(), (e1, e2) -> e1));
        List<MbOrgInfo> allOrgInfo = organizationInfoService.listAll();
        Map<String, MbOrgInfo> orgInfoMap = allOrgInfo.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, Function.identity(), (k1, k2) -> k1));

        if (BooleanUtils.isTrue(req.getIsBackground())) {
            IPage<MbUserRole> iPage = fuzzyByNameOrUserId(req.getEmpName(), Lists.newArrayList(req.getRoleId()), req.getPageNum(), req.getPageSize());
            List<MbUserRole> userRoleList = iPage.getRecords();
            if (CollectionUtils.isNotEmpty(userRoleList)) {
                List<Long> roles = userRoleList.stream().map(MbUserRole::getRoleId).collect(Collectors.toList());
                Map<Long, MbRole> roleMap = roleService.selectRoles(roles).stream()
                    .collect(Collectors.toMap(MbRole::getId, Function.identity(), (k1, k2) -> k1));

                userRoleList.forEach(mbUserRole -> {
                    if (employeeMap.containsKey(mbUserRole.getUid())) {
                        mbUserRole.setEmpName(employeeMap.get(mbUserRole.getUid()).getName());
                        mbUserRole.setEmpEmail(employeeMap.get(mbUserRole.getUid()).getEmail());
                        mbUserRole
                            .setReconciliationEmail(employeeMap.get(mbUserRole.getUid()).getReconciliationEmail());
                    }
                    mbUserRole.setEmpOrgName(Optional.ofNullable(orgInfoMap.get(mbUserRole.getOrgId()))
                        .map(MbOrgInfo::getName).orElse(null));
                    mbUserRole.setRoleOrgName(Optional.ofNullable(orgInfoMap.get(mbUserRole.getRoleOrgId()))
                        .map(MbOrgInfo::getName).orElse(null));
                    mbUserRole.setRoleName(Optional.ofNullable(roleMap.get(mbUserRole.getRoleId()))
                        .map(MbRole::getName).orElse(null));
                });
            }
            return new Page(req.getPageNum(), req.getPageSize(), (int)iPage.getPages(), iPage.getTotal(), userRoleList);
        }

        List<Long> roleIdList = Lists.newArrayList();
        if (req.getRoleId() != null && req.getRoleId() > 0) {
            roleIdList.add(req.getRoleId());
            List<MbRole> mbRoles = roleService.selectByParentId(req.getRoleId());
            if (!CollectionUtils.isEmpty(mbRoles) && mbRoles.size() > 0) {
                roleIdList.addAll(mbRoles.stream().map(MbRole::getId).collect(Collectors.toList()));
            }
        }

        IPage<Object> iPage = PageContext.startPage(req.getPageNum(), req.getPageSize());
        List<MbUserRole> userRoleList = userRoleMapper.fuzzyByUids(uids, null, BaseUtils.filterNull(roleIdList), BaseUtils.filterEmpty(Arrays.asList(req.getRoleOrgId(), req.getCorpId())));

        userRoleList.forEach(e -> {
            if (employeeMap.containsKey(e.getUid())) {
                e.setEmpName(employeeMap.get(e.getUid()).getName());
                e.setEmpEmail(employeeMap.get(e.getUid()).getEmail());
                e.setReconciliationEmail(employeeMap.get(e.getUid()).getReconciliationEmail());
            }
            MbOrgInfo mbOrgInfo = orgInfoMap.get(e.getOrgId());
            if (mbOrgInfo != null){
                e.setEmpOrgName(mbOrgInfo.getName());
            }
        });

        if(CollectionUtils.isNotEmpty(orgIdList)){
            userRoleList = userRoleList.stream()
                    .filter(userRole -> orgIdList.contains(userRole.getOrgId()))
                    .collect(Collectors.toList());

            if(CollectionUtils.isEmpty(userRoleList)){
                userRoleList=Collections.emptyList();
            }
        }

        Page page = new Page(req.getPageNum(), req.getPageSize(), (int) iPage.getPages(), iPage.getTotal(), userRoleList);
        return page;
    }

    public Page pageQueryBg(UserRoleRest.UserRolePageReq req) {
        List<MbOrgEmployeeInfo> employeeInfoList = employeeService.findBgUserByName(req.getEmpName());
        if (CollectionUtils.isEmpty(employeeInfoList)) {
            return new Page(req.getPageNum(), req.getPageSize(), 0, 0L, Collections.emptyList());
        }
        List<String> uids = employeeInfoList.stream().map(MbOrgEmployeeInfo::getUid).collect(Collectors.toList());
        Map<String, MbOrgEmployeeInfo> employeeMap = employeeInfoList.stream().collect(Collectors.toMap(MbOrgEmployeeInfo::getUid, Function.identity(), (e1, e2) -> e1));

        IPage<Object> iPage = PageContext.startPage(req.getPageNum(), req.getPageSize());
        List<MbUserRole> userRoleList = userRoleMapper.fuzzyBgByUids(uids, req.getRoleId(), null);
        userRoleList.forEach(e -> {
            if (employeeMap.containsKey(e.getUid())) {
                e.setEmpName(employeeMap.get(e.getUid()).getName());
                e.setEmpEmail(employeeMap.get(e.getUid()).getEmail());
                e.setReconciliationEmail(employeeMap.get(e.getUid()).getReconciliationEmail());
            }
        });

        Page page = new Page(req.getPageNum(), req.getPageSize(), (int) iPage.getPages(), iPage.getTotal(), userRoleList);
        return page;
    }

    public List<UserRole> searchCorpEmp(List<String> corpIds, String name) {
        List<String> orgIds = BaseUtils.filterEmpty(corpIds);
        if (CollectionUtils.isEmpty(orgIds)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.GET_ORG_ID_NULL);
        }
        List<MbUserRole> result = userRoleMapper.searchCorpEmp(orgIds, name);
        if (CollectionUtils.isEmpty(result)) {
            return null;
        }
        List<UserRole> userRoles = result.stream().filter(Objects::nonNull).map(this::convertUserRole).collect(Collectors.toList());
        if (StringUtils.isNotBlank(name)) {
            userRoles = userRoles.stream().filter(item -> EncryptUtils.sm4Decrypt(item.getUserName()).indexOf(name) > -1).collect(Collectors.toList());
        }
        return userRoles;
    }

    public List<UserRole> searchBgUser(String name) {
        List<MbUserRole> result = userRoleMapper.fuzzyBgByNameNew(true);
        if (CollectionUtils.isEmpty(result)) {
            return null;
        }
        List<UserRole> userRoles = result.stream().filter(Objects::nonNull).map(this::convertUserRole).collect(Collectors.toList());
        if (StringUtils.isNotBlank(name)) {
            userRoles = userRoles.stream().filter(item -> EncryptUtils.sm4Decrypt(item.getUserName()).indexOf(name) > -1).collect(Collectors.toList());
        }
        return userRoles;
    }

    public List<MbUserRole> searchBgIsBackground(Boolean isBackground) {
        return userRoleMapper.fuzzyBgByNameNew(isBackground);
    }

    /**
     * 获取用户角色列表。
     * 1. 只能获取前台用户的前台角色
     * 2. 过滤被删除的角色
     * 3. 过滤被删除的用户
     * 4. 过滤被删除的组织架构
     */
    public Map<UidOrgIdEntry, List<UserRole>> queryRoles(Set<UidOrgIdEntry> identities) {
        List<String> uids = identities.stream()
                .map(UidOrgIdEntry::getUid)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());
        List<UserRole> urs = Optional.ofNullable(fuzzyByName(null, null, null, uids, null)).orElse(new ArrayList<>());
        Map<UidOrgIdEntry, List<UserRole>> result = urs.stream()
                .collect(Collectors.groupingBy(ur -> new UidOrgIdEntry(ur.getUserId(), ur.getUserOrgId())));
        result.keySet()
                .stream()
                .filter(i -> !identities.contains(i))
                .collect(Collectors.toList())
                .forEach(result::remove);
        return result;
    }

    @Override
    public void clearLeft(Set<UidOrgIdEntry> ids) {
        ids.stream().filter(Objects::nonNull).forEach(uidOrgId -> {
            Example e = new Example(MbUserRole.class);
            Example.Criteria c = e.createCriteria();
            if (StringUtils.isNotBlank(uidOrgId.getUid())) {
                c.andEqualTo("uid", uidOrgId.getUid());
            }
            if (StringUtils.isNotBlank(uidOrgId.getOrgId())) {
                c.andEqualTo("orgId", uidOrgId.getOrgId());
            }
            if (CollectionUtils.isEmpty(c.getAllCriteria())) {
                return;
            }
            userRoleMapper.deleteByExample(e);
            roleResourceManager.delUserRoleId(uidOrgId.getUid());
        });
    }

    @Override
    public void clearRight(Set<Long> roleIds) {
        List<Long> ids = roleIds.stream().filter(Objects::nonNull).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }
        Example e = new Example(MbUserRole.class);
        e.createCriteria().andIn("roleId", roleIds);
        userRoleMapper.deleteByExample(e);
    }

    @Override
    @Transactional
    public void batchAssociate(Set<UidOrgIdEntry> leftIds, Set<Long> rightIds) {
        List<Relation<UidOrgIdEntry, Long>> rList = map(leftIds, rightIds);
        rList.stream().map(r -> {
            MbUserRole mur = new MbUserRole();
            mur.setOrgId(r.getLeft().getOrgId());
            if (StringUtils.isBlank(r.getLeft().getUid())) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.UID_NULL);
            }
            mur.setUid(r.getLeft().getUid());
            mur.setRoleId(r.getRight());
            return mur;
        }).forEach(userRoleMapper::insertSelective);
    }

    public void insertOrUpdate(Long userRoleId, UidOrgIdEntry identity, Long roleId) {
        if (identity == null || StringUtils.isBlank(identity.getUid()) || Objects.isNull(roleId)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
        }
        MbUserRole ur = new MbUserRole();
        ur.setRoleId(roleId);
        ur.setId(userRoleId);
        ur.setUid(identity.getUid());
        ur.setOrgId(identity.getOrgId());
        if (userRoleId == null) {
            userRoleMapper.insertSelective(ur);
        } else {
            if (userRoleMapper.selectByPrimaryKey(userRoleId) == null) {
                userRoleMapper.insertSelective(ur);
            } else {
                userRoleMapper.updateByPrimaryKeySelective(ur);
            }
        }
        roleResourceManager.setUserRoleId(identity.getUid(), roleId);
    }

    public List<MbUserRole> getUserRoleByUid(String uid) {

        MbUserRole ur = new MbUserRole();
        ur.setUid(uid);
        return userRoleMapper.select(ur);
    }


    public int insertOrUpdateByUidAndOrgId(UidOrgIdEntry identity, Long roleId) {
        if (identity == null || roleId == null) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
        }
        if (StringUtils.isBlank(identity.getUid()) || StringUtils.isBlank(identity.getOrgId())) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
        }
        roleResourceManager.setUserRoleId(identity.getUid(), roleId);
        Example e = new Example(MbUserRole.class);
        Example.Criteria c = e.createCriteria();
        c.andEqualTo("uid", identity.getUid())
                .andEqualTo("orgId", identity.getOrgId());
        if (userRoleMapper.selectOneByExample(e) == null) {
            insertOrUpdate(null, identity, roleId);
            return 1;
        } else {
            MbUserRole selectParam = new MbUserRole();
            selectParam.setRoleId(roleId);
            selectParam.setUid(identity.getUid());
            selectParam.setOrgId(identity.getOrgId());
            return userRoleMapper.updateByExampleSelective(selectParam, e);
        }
    }

    public Page searchUserRole(SearchUserRoleRequest request) {
        //获取角色用户分页数据

        IPage<MbUserRole> page;
        if (request.getIsBackground()) {
            page = this.fuzzyByNameOrUserId(request.getContent(), null, request.getPageNum(), request.getPageSize());
        } else {
            List<String> orgIds = null;
            if (StringUtils.isNotBlank(request.getOrgId())) {
                orgIds = organizationInfoService.listRecentCompanyAllDepartmentByOrgId(request.getOrgId());
                if (CollectionUtils.isEmpty(orgIds)) {
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.GET_ORG_ID_NULL);
                }
            }
            page = PageContext.startPage(request.getPageNum(), request.getPageSize());
            userRoleMapper.fuzzyByOrgIdandUidorName(request.getIsBackground(), orgIds, request.getContent());
        }
        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            List<Long> roles = page.getRecords().stream().map(MbUserRole::getRoleId).collect(Collectors.toList());
            Map<Long, MbRole> roleMap = org.springframework.util.CollectionUtils.isEmpty(roles)
                    ? Collections.emptyMap() :
                    roleService.selectRoles(roles).stream().collect(Collectors.toMap(MbRole::getId, Function.identity(), (k1, k2) -> k1));
            return new Page((int) page.getCurrent(), (int) page.getSize(), (int) page.getPages(), page.getTotal(), page.getRecords().stream().map(x -> convert(x, roleMap)).collect(Collectors.toList()));
        }
        return null;
    }

    public IPage<MbUserRole> fuzzyByNameOrUserId(String content, List<Long> roleIds, Integer pageNum,
        Integer pageSize) {
        List<String> userIds = new ArrayList<>();
        if (StringUtils.isNotBlank(content)) {
            List<MbOrgEmployeeInfo> employeeInfoList = employeeService.findBgUserByName(content);
            if (CollectionUtils.isNotEmpty(employeeInfoList)) {
                userIds.addAll(employeeInfoList.stream().map(MbOrgEmployeeInfo::getUid).collect(Collectors.toList()));
            }
        }
        log.info("fuzzyByNameOrUserId:{}", JsonUtils.toJsonString(userIds));
        IPage<MbUserRole> page = PageContext.startPage(pageNum, pageSize);
        roleIds = Optional.ofNullable(roleIds).orElse(Collections.emptyList())
            .stream().filter(Objects::nonNull)
            .collect(Collectors.toList());
        userRoleMapper.fuzzyByNameOrUserId(content, userIds, roleIds);
        return page;
    }

    private MbUserRoleInfo convert(MbUserRole ur, Map<Long, MbRole> roleMap) {
        if (ur == null) {
            return null;
        }

        MbUserRoleInfo result = new MbUserRoleInfo();
        result.setId(ur.getId());
        result.setRoleId(ur.getRoleId());
        result.setAccountName(ur.getEmpName());
        result.setStaffNumber(ur.getUid());
        result.setOrgId(ur.getOrgId());
        result.setPhone(ur.getEmpMobilePhone());
        result.setAreaCode(ur.getEmpAreaCode());
//        result.setDepartmentName();
        result.setRoleName(Objects.nonNull(ur.getRoleId()) ? roleMap.get(ur.getRoleId()).getName() : "");

        return result;
    }

    /**
     * 删除用户角色关联关系
     */
    @Transactional
    public void deleteUserRole(String staffNumber) {
        Example example = new Example(MbUserRole.class);
        example.createCriteria().andEqualTo("uid", staffNumber);
        userRoleMapper.deleteByExample(example);
        boolean flag = userLoginService.deleteByUid(staffNumber);
        if (!flag) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.DEL_LOGIN_INFO_ERROR);
        }
        // 删除用户信息
        boolean delete = employeeService.deleteByUid(staffNumber);
        if (!delete) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.DEL_EMPLOYEE_INFO_ERROR);
        }
        // 删除用户证件信息
        orgUserIdCardService.deleteByEmployeeUid(staffNumber);
    }

    public RoleInfoPojo convertPojo(ListRoleReq req) {
        List<UserRole> userRoles = this.listRole(Collections.singletonList(req.getCorpId()));
        if (CollectionUtils.isEmpty(userRoles)) {
            return null;
        }
        List<RoleRest.RoleInfo> lists = userRoles.stream()
                .collect(Collectors.groupingBy(UserRole::getRoleId))
                .values()
                .stream()
                .map(urList -> {
                    RoleRest.RoleInfo r = new RoleRest.RoleInfo();
                    r.setUserCount((int) urList.stream()
                            .filter(ur -> new Date(0).equals(ur.getEmpDeleteTime()))
                            .filter(ur -> StringUtils.isNotBlank(ur.getUserId())).count());
                    r.setName(urList.get(0).getRoleName());
                    r.setId(urList.get(0).getRoleId());
                    r.setDataChangeTime(urList.get(0).getDataChangeTime());
                    r.setDescription(urList.get(0).getDescription());
                    return r;
                })
                .sorted((r1, r2) -> -Comparator.comparing(RoleRest.RoleInfo::getDataChangeTime).compare(r1, r2))
                .collect(Collectors.toList());

        if (CollectionUtils.isNotEmpty(lists)) {
            RoleInfoPojo convertPojo = new RoleInfoPojo();
            RoleRest.RoleInfo roleInfo = lists.get(0);
            convertPojo.setName(roleInfo.getName());
            convertPojo.setDesc(roleInfo.getDescription());
            return convertPojo;
        }

        return null;
    }


    public UserRolePojo convert(UserRoleRest.UserRolePageReq req) {
        Page page = this.pageQuery(req);

        if (CollectionUtils.isNotEmpty(page.getList())) {
            List<MbUserRole> mbUserRoleList = (List<MbUserRole>) page.getList();
            List<UserRoleRest.UserRoleInfo> userRoleInfoList = new ArrayList<>();
            mbUserRoleList.forEach(ur -> {
                UserRoleRest.UserRoleInfo urpr = new UserRoleRest.UserRoleInfo();
                urpr.setId(ur.getId());
                urpr.setUserId(ur.getUid());
                urpr.setRoleId(ur.getRoleId());
                urpr.setUserName(ur.getEmpName());
                urpr.setUserOrgId(ur.getEmpOrgId());
                urpr.setUserOrgName(ur.getEmpOrgName());
                urpr.setRoleName(ur.getRoleName());
                urpr.setRoleOrgId(ur.getRoleOrgId());
                urpr.setRoleOrgName(ur.getRoleOrgName());
                urpr.setMobilePhone(ur.getEmpMobilePhone());
                urpr.setCountryCode(ur.getEmpAreaCode());
                userRoleInfoList.add(urpr);
            });
            return JsonUtils.convert(userRoleInfoList, UserRolePojo.class);
        }
        return null;
    }

    /**
     * 根据orgId查询
     *
     * @param roleIdList
     * @return
     */
    public List<MbUserRole> listByRoleIdList(List<Long> roleIdList) {
        if (CollectionUtils.isEmpty(roleIdList)) {
            return new ArrayList<>();
        }
        Example example = new Example(MbUserRole.class);
        example.createCriteria().andIn("roleId", roleIdList);
        return Optional.ofNullable(userRoleMapper.selectByExample(example)).orElse(new ArrayList<>());
    }

    public JSONResult<Long> findRoleIdByUidAndOrgId(String orgId, String uid) {
        Example example = new Example(MbUserRole.class);
        example.createCriteria().andEqualTo("uid", uid).andEqualTo("orgId", orgId);
        List<MbUserRole> mbUserRoles = userRoleMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(mbUserRoles)) {
            return JSONResult.success(mbUserRoles.get(0).getRoleId());
        }
        return JSONResult.success(null);
    }
}
